package com.amt.olcacon;

import java.util.*;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ExchangeTreeBuilder {
    
    // 构建完整的交换树
    public TreeNode buildExchangeTree(List<Exchange> exchanges, List<Product> products) {
        // 创建根节点
        TreeNode root = new TreeNode("交换表树状结构");
        
        // 为每个交换记录构建子树
        for (Exchange exchange : exchanges) {
            TreeNode exchangeNode = buildExchangeSubtree(exchange, exchanges, products, new HashSet<>());
            root.addChild(exchangeNode);
        }
        
        return root;
    }
    
    // 递归构建交换子树
    private TreeNode buildExchangeSubtree(Exchange currentExchange, 
                                         List<Exchange> allExchanges, 
                                         List<Product> allProducts,
                                         Set<Long> visitedIds) {
        
        TreeNode currentNode = new TreeNode(currentExchange.getName());
        
        // 防止循环引用
        if (visitedIds.contains(currentExchange.getId())) {
            return currentNode;
        }
        
        visitedIds.add(currentExchange.getId());
        
        // 查找当前交换记录的提供者产品
        Product providerProduct = findProductById(allProducts, currentExchange.getProviderId());
        if (providerProduct != null) {
            TreeNode productNode = new TreeNode(providerProduct.getName());
            currentNode.addChild(productNode);
            
            // 查找提供者产品的所有交换记录，并递归构建子树
            List<Exchange> providerExchanges = findExchangesByProductId(allExchanges, providerProduct.getId());
            for (Exchange providerExchange : providerExchanges) {
                TreeNode subTree = buildExchangeSubtree(providerExchange, allExchanges, allProducts, new HashSet<>(visitedIds));
                productNode.addChild(subTree);
            }
        }
        
        return currentNode;
    }
    
    // 辅助方法：根据ID查找产品
    private Product findProductById(List<Product> products, Long id) {
        return products.stream()
                .filter(p -> p.getId().equals(id))
                .findFirst()
                .orElse(null);
    }
    
    // 辅助方法：根据产品ID查找交换记录
    private List<Exchange> findExchangesByProductId(List<Exchange> exchanges, Long productId) {
        List<Exchange> result = new ArrayList<>();
        for (Exchange exchange : exchanges) {
            if (exchange.getProductId().equals(productId)) {
                result.add(exchange);
            }
        }
        return result;
    }
    
    // 将树转换为JSON字符串
    public String convertToJson(TreeNode root) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(root);
    }
}